package com.hyrluntan.forum.services.impl;

import com.hyrluntan.forum.common.AppResult;
import com.hyrluntan.forum.common.ResultCode;
import com.hyrluntan.forum.dao.UserMapper;
import com.hyrluntan.forum.exception.ApplicationException;
import com.hyrluntan.forum.model.User;
import com.hyrluntan.forum.services.IUserService;
import com.hyrluntan.forum.utils.MD5Util;
import com.hyrluntan.forum.utils.StringUtil;
import com.hyrluntan.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        // 1、非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())||StringUtil.isEmpty(user.getNickname())
                ||StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getSalt())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2、根据用户名查询当前⽤⼾是否存在
        User existUser = userMapper.selectByUserName(user.getUsername());
        // 判断用户是否存在
        if (existUser != null) {
            // 记录⽇志
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username = " + user.getUsername());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3、新增用户信息
        // 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
            // 性别赋默认值
            user.setGender((byte) 2);
        }
        // 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            // 记录⽇志
            log.info(ResultCode.FAILED_CREATE.toString() + "username = " + user .getUsername());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 记录⽇志
        log.info("新增⽤⼾成功：username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 调⽤Mapper中的⽅法，根据⽤⼾名查询⽤⼾信息
        return userMapper.selectByUserName(username);
    }

//    @Override
//    public User login(String username, String password,String verificationCode) {
//        // 非空校验
//        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)||StringUtil.isEmpty(verificationCode)){
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
//        }
//
//
//        // 根据⽤⼾名获取⽤⼾信息
//        User user = selectByUserName(username);
//        // ⽤⼾不存在抛出异常
//        if (user == null) {
//            log.warn(ResultCode.FAILED_LOGIN.toString() + " , username = " + username);
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
//        }
//        // 校验密码是否正确
//        String encryptPassword = MD5Util. md5Salt (password, user.getSalt());
//        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
//            log .info(ResultCode. FAILED_LOGIN .toString() + "密码错误 : username = " + username + ", password = " + password);
//            throw new ApplicationException(AppResult. failed (ResultCode. FAILED_LOGIN ));
//        }
//        log.info("登录成功，username = "+username);
//        // 校验通过，返回⽤⼾信息
//        return user;
//    }

//    @Override
//    public User login(String username, String password) {
//        // 非空校验
//        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
//            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
//        }
//        // 根据⽤⼾名获取⽤⼾信息
//        User user = selectByUserName(username);
//        // ⽤⼾不存在抛出异常
//        if (user == null) {
//            log.warn(ResultCode.FAILED_LOGIN.toString() + " , username = " + username);
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
//        }
//        // 校验密码是否正确
//        String encryptPassword = MD5Util. md5Salt (password, user.getSalt());
//        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
//            log .info(ResultCode. FAILED_LOGIN .toString() + "密码错误 : username = " + username + ", password = " + password);
//            throw new ApplicationException(AppResult. failed (ResultCode. FAILED_LOGIN ));
//        }
//        log.info("登录成功，username = "+username);
//        // 校验通过，返回⽤⼾信息
//        return user;
//    }

    @Override
    public User login(String username, String password) {
        // 非空校验
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 根据⽤⼾名获取⽤⼾信息
        User user = selectByUserName(username);
        // ⽤⼾不存在抛出异常
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + " , username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 校验密码是否正确
        String encryptPassword = MD5Util. md5Salt (password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log .info(ResultCode. FAILED_LOGIN .toString() + "密码错误 : username = " + username + ", password = " + password);
            throw new ApplicationException(AppResult. failed (ResultCode. FAILED_LOGIN ));
        }

        log.info("登录成功，username = "+username);
        // 校验通过，返回⽤⼾信息
        return user;
    }
    @Override
    public User selectById(Long id) {
        // 非空校验
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 调用DAO查询数据库并获取对象
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询⽤⼾信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新⽤⼾的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询⽤⼾信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新⽤⼾的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1之后，⽤⼾的发帖数是否⼩于0
        if (updateUser.getArticleCount() < 0) {
            // 如果⼩于0，则设置为0
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        // 1. ⾮空校验
        if (user == null || user.getId() == null || user.getId() < 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2. 校验⽤⼾是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 3. 定义⼀个标志位
        boolean checkAttr = false; // false表⽰没有校验通过
        // 4. 定义⼀个专⻔⽤来更新的对象，防⽌⽤⼾传⼊的User对象设置了其他的属性
        // 当使⽤动态SQL进⾏更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        // 5. 设置⽤⼾Id
        updateUser.setId(user.getId());
        // 6. 对每个⼀个参数进⾏校验并赋值
        if (!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(existsUser.getUsername())) {
            // 需要更新⽤⼾名(登录名)时，进⾏唯⼀性的校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            // 数据库中没有找到相应的⽤⼾，表⽰可以修改⽤⼾名
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        // 7. 校验昵称
        if (!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        // 8. 校验性别
        if (user.getGender() != null && user.getGender() != existsUser.getGender()) {
            updateUser.setGender(user.getGender());
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }
        // 9. 校验邮箱
        if (!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }
        // 9. 校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        // 10. 校验个⼈简介
        if (!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        // 11. 根据标志位来决定是否可以执⾏更新
        if (checkAttr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 12. 调⽤DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的⾏数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id==null||id<0||StringUtil.isEmpty(newPassword)||StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null||user.getDeleteState()==1) {
            log .info(ResultCode. FAILED_USER_NOT_EXISTS .toString() + "user id = " + id);
            throw new ApplicationException(AppResult. failed (ResultCode. FAILED_USER_NOT_EXISTS ));
        }
        // 校验原密码是否正确
        String oldEncryptPassword = MD5Util. md5Salt (oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log .info(ResultCode. FAILED_PARAMS_VALIDATE .toString() + "username = " +
                    user.getUsername() + ", password = " + oldPassword);
            throw new ApplicationException(AppResult. failed (ResultCode. FAILED_PARAMS_VALIDATE ));
        }
        // 重新⽣成扰动字符串
        String salt = UUIDUtil.UUID_32 ();
        // 计算新密码
        String encryptPassword = MD5Util.md5Salt(newPassword, salt);
        // 创建⽤于更新的User对象
        User modifyUser = new User();
        modifyUser.setId(user.getId());
        modifyUser.setPassword(encryptPassword);
        modifyUser.setSalt(salt);
        modifyUser.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(modifyUser);
        log .info("⽤⼾密码修改成功：" + user.getUsername());
    }
}
